package org.csu.onlineedubackend.util;

import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 验证码工具类
 */
@Component
public class CaptchaUtil {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 生成验证码
     * @return 包含验证码图片和key的Map
     */
    public Map<String, Object> generateCaptcha() {
        // 生成验证码
        SpecCaptcha captcha = new SpecCaptcha(130, 48, 5);
        captcha.setCharType(Captcha.TYPE_DEFAULT); // 字母数字混合
        
        // 生成验证码的文本内容
        String captchaCode = captcha.text().toLowerCase();
        
        // 生成唯一key
        String key = UUID.randomUUID().toString();
        
        // 存入Redis，设置2分钟过期
        redisTemplate.opsForValue().set("captcha:" + key, captchaCode, 2, TimeUnit.MINUTES);
        
        // 构建返回数据
        Map<String, Object> result = new HashMap<>();
        result.put("captchaKey", key);
        result.put("captchaImage", captcha.toBase64());
        
        return result;
    }
} 